package com.mkk.deskTopSearch.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Date;

/**
 * 2010-8-14 下午11:26:50
 * 
 * @author mkk 日志处理工具类
 */
public class LogUtil {

	// 当前日期对象及格式,用于生成日志文件名
	private static Date date = new Date();
	private static String format = "yyyyMMdd";

	/**
	 * 获取保存异常日志的文件<br>
	 * 根据日期来获取
	 * 
	 * @return
	 * @throws IOException
	 */
	public static File getSaveExceptionFile() throws IOException {
		File f = new File(PropertiesUtil.LOG_PATH + File.separator
				+ SystemUtil.formatDate(date, format) + ".log");
		if (!f.exists()) {
			f.createNewFile();
		}
		return f;
	}

	/**
	 * 获取保存创建索引的日志文件<br>
	 * 根据日期来获取
	 * 
	 * @return
	 * @throws IOException
	 */
	public static File getCreatIndexFile() throws IOException {
		File f = new File(PropertiesUtil.LOG_PATH + File.separator
				+ SystemUtil.formatDate(date, format) + "-index.log");
		if (!f.exists()) {
			f.createNewFile();
		}
		return f;
	}

	/**
	 * 获取创建索引日志的输出流对象
	 * 
	 * @return 若创建异常则返回null
	 */
	public static PrintStream getCreatIndexStream() {
		PrintStream ps = null;
		try {
			ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(
					getCreatIndexFile(), true)),true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ps;
	}

	/**
	 * 保存异常日志信息
	 * 
	 * @param e
	 */
	public static void saveExceptionLog(final Exception e) {
		if (e == null) {
			return;
		}
		new Thread() {
			public void run() {
				PrintWriter pw = null;
				try {
					pw = new PrintWriter(new FileWriter(getSaveExceptionFile(),
							true));
					e.printStackTrace(pw);
				} catch (Exception ex) {
					System.out.println("保存异常日志时异常,信息: " + e.getMessage());
				} finally {
					if (pw != null) {
						pw.close();
					}
				}
			}
		}.start();
	}

}
